package com.fashion.web.actions.management.gallery;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import com.fashion.model.gallery.Album;
import com.fashion.model.gallery.Photo;
import com.fashion.service.gallery.AlbumService;
import com.fashion.service.gallery.PhotoService;
import com.fashion.utils.Variable;
import com.opensymphony.xwork2.ActionSupport;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;

@Controller
@ParentPackage("json-default")
@Namespace("/management/gallery")
public class AlbumAdminAction extends ActionSupport {
	private Photo photo = new Photo();
	private Album album = new Album();
	private File uploadify;
	private String uploadifyFileName;
	private String autoZoomPhoto = "false";
	private String autoZoomCover = "false";
	private String coverType;
	@Resource(name = "photoService")
	private PhotoService photoService;
	@Resource(name = "albumService")
	private AlbumService albumService;

	@Action(value = "find_photos_by_album", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "columns"}) })
	public String find() throws Exception {
		album = albumService.findById(album.getId());
		return SUCCESS;
	}

	@Action(value = "add_photo", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "album.photoList" }) })
	public String add() throws Exception {
		album = albumService.findById(album.getId());
		String extName = "";
		if (uploadifyFileName.lastIndexOf(".") >= 0) {
			extName = uploadifyFileName.substring(uploadifyFileName
					.lastIndexOf("."));
		}

		if (".zip".equals(extName) || ".rar".equals(extName)) {
			String folderPre = ServletActionContext.getServletContext()
					.getRealPath(Variable.PHOTO_DIR_SUBSTR);
			String folder = folderPre + File.separator + album.getId();
			
			if (".rar".equals(extName)) {
				Archive arch = new Archive(uploadify);
				FileHeader fh = arch.nextFileHeader();
				int index = 0;
				while (fh != null) {
					if (!fh.isDirectory()) {
						Photo photo = new Photo();
						photo.setAlbum(album);
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						arch.extractFile(fh, out);
						BufferedInputStream bis = new BufferedInputStream(
								new ByteArrayInputStream(out.toByteArray()));
						String nowTime = new SimpleDateFormat("yyyymmddHHmmss")
								.format(new Date());
						extName = fh.getFileNameString().substring(
								fh.getFileNameString().lastIndexOf("."));
						index++;
						String saveName = nowTime + index + extName;
						photo.setName(saveName);
						photoService.savePhoto(bis, saveName, folder, "true"
								.equals(autoZoomPhoto));
						photoService.addPhoto(photo);
						bis.close();
					}
					fh = arch.nextFileHeader();
				}
				arch.close();

			}
			if (".zip".equals(extName)) {

				ZipFile zipFile = new ZipFile(uploadify);
				Enumeration emu = zipFile.entries();
				int index = 0;
				while (emu.hasMoreElements()) {
					ZipEntry entry = (ZipEntry) emu.nextElement();
					if (!entry.isDirectory()) {
						Photo photo = new Photo();
						photo.setAlbum(album);
						BufferedInputStream bis = new BufferedInputStream(
								zipFile.getInputStream(entry));
						index++;
						String nowTime = new SimpleDateFormat("yyyymmddHHmmss")
								.format(new Date());
						extName = entry.getName().substring(
								entry.getName().lastIndexOf("."));
						String saveName = nowTime + index + extName;
						photo.setName(saveName);
						
						photoService.savePhoto(bis, saveName, folder, "true"
								.equals(autoZoomPhoto));
						photoService.addPhoto(photo);
		
						bis.close();
					}

				}
				zipFile.close();
			}
		} else {
			Photo photo = new Photo();
			String nowTime = new SimpleDateFormat("yyyymmddHHmmss")
					.format(new Date());
			String saveName = nowTime + extName;
			photo.setName(saveName);
			photo.setAlbum(album);
			String folderPre = ServletActionContext.getServletContext()
					.getRealPath(Variable.PHOTO_DIR_SUBSTR);
			String folder = folderPre + File.separator + album.getId();
			photoService.savePhoto(new FileInputStream(uploadify), saveName,
					folder, "true".equals(autoZoomPhoto));
			photoService.addPhoto(photo);
		}
		return SUCCESS;
	}

	@Action(value = "delete_photo", results = { @Result(name = SUCCESS, location = "album.jsp") })
	public String delete() throws Exception {
		photo = photoService.findById(photo.getId());
		String folderPre = ServletActionContext.getServletContext()
				.getRealPath(Variable.PHOTO_DIR_SUBSTR);
		String folder = folderPre + File.separator + photo.getAlbum().getId();

		photoService.delPhoto(photo, folder);
		return SUCCESS;
	}

	@Action(value = "album_index", results = { @Result(name = SUCCESS, location = "album.jsp") })
	public String index() throws Exception {
		album = albumService.findById(album.getId());
		return SUCCESS;
	}

	@Action(value = "set_cover", results = { @Result(name = SUCCESS, location = "album.jsp") })
	public String setCover() throws Exception {
		photo = photoService.findById(photo.getId());
		String extName = "";
		String name = photo.getName();
		if (name.lastIndexOf(".") >= 0) {
			extName = name.substring(name.lastIndexOf("."));
		}
		album = photo.getAlbum();
		// albumService.setCover(album.getId(),photo.getName());
		String folderPre = ServletActionContext.getServletContext()
				.getRealPath(Variable.PHOTO_DIR_SUBSTR);
		String folder = folderPre + File.separator + album.getId();
		File src = new File(folder + File.separator + photo.getName());
		String dest = folder + File.separator + Variable.COVER_DIR_SUBSTR;
		String saveName = album.getId() + extName;
		if ("TRANSVERSE_COVER".equals(coverType)) {
			albumService.saveTransverseCover(src, saveName, dest, "true"
					.equals(autoZoomCover));
		} else {
			albumService.saveLognitudinalCover(src, saveName, dest, "true"
					.equals(autoZoomCover));
		}
		albumService.updateCover(album.getId(), saveName);
		return SUCCESS;
	}

	public Photo getPhoto() {
		return photo;
	}

	public void setPhoto(Photo photo) {
		this.photo = photo;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}

	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	public Album getAlbum() {
		return album;
	}

	public void setAlbum(Album album) {
		this.album = album;
	}

	public void setAutoZoomPhoto(String autoZoomPhoto) {
		this.autoZoomPhoto = autoZoomPhoto;
	}

	public void setAutoZoomCover(String autoZoomCover) {
		this.autoZoomCover = autoZoomCover;
	}

	public void setCoverType(String coverType) {
		this.coverType = coverType;
	}

}
